package com.novel.crawl.common.filter;

import com.novel.crawl.common.service.BookService;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 奔波儿灞
 * @since 1.0
 */
public class ViewFilter extends OncePerRequestFilter {

    private static final Logger LOG = LoggerFactory.getLogger(ViewFilter.class);

    /**
     * 过滤
     */
    public static final String FILTER_CHAPTER_PATTERN = "/chapter/*";
    public static final String FILTER_CONTENT_PATTERN = "/content/*";

    /**
     * 请求头携带访问的bookId
     */
    private static final String HEADER_VIEW = "View-BookId";

    private final BookService bookService;

    public ViewFilter(BookService bookService) {
        this.bookService = bookService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (HttpMethod.GET.matches(request.getMethod())) {
            String bookId = request.getHeader(HEADER_VIEW);
            if (StringUtils.isNotEmpty(bookId) && ObjectId.isValid(bookId)) {
                LOG.debug("book view, bookId: {}", bookId);
                bookService.incrementView(bookId);
            }
        }
        filterChain.doFilter(request, response);
    }

}
